<template>
  <el-dialog v-model="dialogVisible" :title="title" width="500px" @close="handleClose">
    <div class="import-dialog-qvil">
      <div class="import-tips">
        <slot name="tip">
          <div class="tip-item">
            <el-icon><info-filled /></el-icon>
            <span>请先下载导入模板，按模板格式填写数据</span>
          </div>
          <div class="tip-item">
            <el-icon><info-filled /></el-icon>
            <span>支持的文件格式：{{ fileTypes.join('、') }}</span>
          </div>
        </slot>
      </div>

      <el-upload
        ref="uploadRef"
        :accept="acceptTypes"
        action="#"
        :auto-upload="false"
        :before-upload="beforeUpload"
        class="upload-area"
        :limit="1"
        :on-change="handleFileChange"
        :show-file-list="true"
      >
        <el-button type="primary">
          <el-icon><upload /></el-icon>
          选择文件
        </el-button>
      </el-upload>

      <div class="dialog-footer">
        <el-button :loading="downloadLoading" plain type="primary" @click="handleDownloadTemplate">
          <el-icon v-if="!downloadLoading"><download /></el-icon>
          下载导入模板
        </el-button>
        <div class="action-buttons">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button :disabled="!hasFile || uploading" type="primary" @click="submitUpload">
            <el-icon v-if="uploading"><loading /></el-icon>
            {{ uploading ? '导入中...' : '开始导入' }}
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Download, InfoFilled, Loading, Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, ref, watch } from 'vue'

const props = defineProps({
  // 基本属性
  modelValue: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '批量导入',
  },
  activityId: {
    type: String,
    default: '',
  },

  // 文件配置
  fileTypes: {
    type: Array as () => string[],
    default: () => ['xlsx', 'xls'],
  },

  // API配置 - 可以直接传入API函数
  importApi: {
    type: Function,
    default: null,
  },
  templateApi: {
    type: Function,
    default: null,
  },
})

const emit = defineEmits(['update:modelValue', 'success', 'error', 'close'])

// 状态
const dialogVisible = ref(props.modelValue)
const uploadRef = ref()
const fileList = ref<Array<any>>([])
const hasFile = computed(() => fileList.value.length > 0)
const uploading = ref(false)
const downloadLoading = ref(false)

// 监听model-value变化
watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val
  }
)

// 监听对话框状态变化
watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:modelValue', val)
  }
)

// 计算接受的文件类型
const acceptTypes = computed(() => {
  return props.fileTypes.map((type) => `.${type}`).join(',')
})

// 文件变更处理
const handleFileChange = (file: any, files: any[]) => {
  fileList.value = files
}

// 上传前验证
const beforeUpload = (file: any) => {
  const isValidType = props.fileTypes.some((type) => file.name.toLowerCase().endsWith(`.${type.toLowerCase()}`))

  if (!isValidType) {
    ElMessage.error(`请上传${props.fileTypes.join('或')}格式的文件`)
    return false
  }

  const maxSize = 2 * 1024 * 1024 // 2MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过2MB')
    return false
  }

  return true
}

// 下载导入模板
const handleDownloadTemplate = async () => {
  if (!props.templateApi) {
    ElMessage.error('未配置下载模板API')
    return
  }

  downloadLoading.value = true
  try {
    const response = await props.templateApi()

    // 检查响应是否成功
    if (response.code !== 0) {
      throw new Error(response.message || '下载模板失败')
    }

    // 直接使用返回的文件路径
    const filePath = response.result
    const baseUrl = import.meta.env.VITE_APP_BASE_URL || ''
    const fullPath = `${baseUrl}/${filePath}`

    // 创建下载链接
    const link = document.createElement('a')
    link.href = fullPath
    link.target = '_blank'
    const fileName = filePath.split('/').pop() || '导入模板.xlsx'
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('模板下载成功')
  } catch (error: any) {
    console.error('下载模板失败', error)
    ElMessage.error(`下载模板失败: ${error.message || '请稍后重试'}`)
  } finally {
    downloadLoading.value = false
  }
}

// 提交上传
const submitUpload = async () => {
  if (!hasFile.value) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }

  if (!props.importApi) {
    ElMessage.error('未配置导入API')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()
    const file = fileList.value[0].raw
    formData.append('file', file)

    // 如果有activityId参数，需要添加到上传数据中
    if (props.activityId) {
      formData.append('activityId', props.activityId)
    }

    // 调用导入API
    const response = await props.importApi(formData)

    // 检查响应是否成功
    if (response && response.code === 0) {
      // 处理成功结果，传递result部分
      handleSuccess(response.result)
    } else {
      // 处理失败情况
      throw new Error(response.message || '导入失败')
    }
  } catch (error: any) {
    // 记录错误信息
    console.error('导入操作失败:', error)

    // 针对网络错误添加特殊提示
    if (error.name === 'NetworkError' || error.message?.includes('network') || !navigator.onLine) {
      ElMessage.error('网络连接异常，请检查网络后重试')
    } else {
      ElMessage.error(`导入失败: ${error.message || '未知错误'}`)
    }

    // 通知外部组件发生了错误
    handleError(error)
  } finally {
    // 确保无论如何都会重置上传状态
    uploading.value = false
  }
}

// 导入成功
const handleSuccess = (result: any) => {
  // result已经是包含all/success/error的对象
  console.log('处理成功响应:', result)

  // 直接处理统计数据
  const totalCount = result?.all || 0
  const successCount = result?.success || 0
  const errorCount = result?.error || 0

  // 构建成功消息
  let successMessage
  if (errorCount > 0) {
    successMessage = `导入完成，共 ${totalCount} 条，成功 ${successCount} 条，失败 ${errorCount} 条`
  } else {
    successMessage = `导入成功，共导入 ${successCount} 条数据`
  }

  ElMessage.success(successMessage)
  emit('success', result)
  dialogVisible.value = false
}

// 导入失败
const handleError = (error: any) => {
  // 不再检查error对象中是否包含成功数据
  emit('error', error)
}

// 关闭处理
const handleClose = () => {
  // 重置组件状态
  fileList.value = []
  uploading.value = false
  emit('close')
}

// 打开对话框
const open = () => {
  dialogVisible.value = true
}

// 关闭对话框
const close = () => {
  dialogVisible.value = false
}

// 对外暴露方法
defineExpose({
  open,
  close,
  uploadRef,
  fileList,
  uploading,
  // 提供一个重置方法供外部使用
  reset: () => {
    fileList.value = []
    uploading.value = false
    uploadRef.value?.clearFiles?.()
  },
})
</script>

<style lang="scss" scoped>
.import-dialog-qvil {
  padding: 0 20px;

  .import-tips {
    margin-bottom: 20px;

    .tip-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      color: var(--el-color-warning);

      .el-icon {
        margin-right: 8px;
      }
    }
  }

  .upload-area {
    margin-bottom: 20px;
  }

  .dialog-footer {
    margin-top: 30px;
    display: flex;
    justify-content: space-between;

    .action-buttons {
      display: flex;
      gap: 8px;
    }

    .el-icon {
      margin-right: 8px;
    }
  }
}
</style>
